package com.aaa.sbm.service.impl;

import com.aaa.sbm.dao.ProductDao;
import com.aaa.sbm.entity.Product;
import com.aaa.sbm.service.ProductService;
import com.aaa.sbm.util.Result;
import com.aaa.sbm.common.ResultUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ProductServiceImpl implements ProductService {
    
    @Resource
    private ProductDao productDao;
    
    @Override
    @Transactional
    public Result addProduct(Product product) {
        // 检查商品编码是否已存在
        Product existProduct = productDao.selectByCode(product.getProductCode());
        if (existProduct != null) {
            return ResultUtil.fail("商品编码已存在");
        }
        
        int rows = productDao.insert(product);
        return rows > 0 ? ResultUtil.success("添加成功") : ResultUtil.fail("添加失败");
    }
    
    @Override
    @Transactional
    public Result updateProduct(Product product) {
        // 检查商品是否存在
        Product existProduct = productDao.selectById(product.getId());
        if (existProduct == null) {
            return ResultUtil.fail("商品不存在");
        }
        
        // 如果修改了商品编码，需要检查新编码是否已存在
        if (!existProduct.getProductCode().equals(product.getProductCode())) {
            Product codeExist = productDao.selectByCode(product.getProductCode());
            if (codeExist != null) {
                return ResultUtil.fail("商品编码已存在");
            }
        }
        
        int rows = productDao.update(product);
        return rows > 0 ? ResultUtil.success("更新成功") : ResultUtil.fail("更新失败");
    }
    
    @Override
    @Transactional
    public Result deleteProduct(Integer id) {
        // 检查商品是否存在
        Product product = productDao.selectById(id);
        if (product == null) {
            return ResultUtil.fail("商品不存在");
        }
        
        // 检查商品是否有库存
        if (product.getStock() > 0) {
            return ResultUtil.fail("商品还有库存，不能删除");
        }
        int rows = productDao.deleteById(id);
        return rows > 0 ? ResultUtil.success("删除成功") : ResultUtil.fail("删除失败");
    }
    
    @Override
    public Result getProduct(Integer id) {
        Product product = productDao.selectById(id);
        if (product == null) {
            return ResultUtil.fail("商品不存在");
        }
        return ResultUtil.success(product);
    }
    
    @Override
    public Result getProductList(Product product, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Product> list = productDao.selectList(product);
        PageInfo<Product> pageInfo = new PageInfo<>(list);
        return ResultUtil.success(pageInfo);
    }
    
    @Override
    public Result getLowStockProducts() {
        List<Product> list = productDao.selectLowStock();
        return ResultUtil.success(list);
    }
} 